package com.yunhe.dtu.util;

import com.yunhe.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ResourceUtils;
import org.yaml.snakeyaml.Yaml;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName YmlUtils
 * @Description 读取yml 配置的工具类
 * @Author HeTao
 * @Date 2020/11/17 11:02
 * @Version 1.0
 **/
public class YmlUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(YmlUtils.class);

    private static String bootstrap_file = "classpath:mapping/control.yml";

    private static Map<String,String> result = new HashMap<>();

    /**
     * 根据文件名获取yml的文件内容
     * @param filePath
     * @param keys 第一个参数对应第一个key，第二个参数对应第二个key 比如spring.name下的所有 就是两个参数、
     *       getYmlByFileName(bootstrap_file,"spring", "name");
     * @return
     */
    public static Map<String,String> getYmlByFileName(String filePath, String... keys) {
        result = new HashMap<>();
        if(filePath == null) {
            filePath = bootstrap_file;
        }
        InputStream in = null;
        try {
//            File file = ResourceUtils.getFile(filePath);
//            in = new BufferedInputStream(new FileInputStream(file));
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(filePath);
            Resource resource = resources[0];//获得文件流，因为在jar文件中，不能直接通过文件资源路径拿到文件，但是可以在jar包中拿到文件流
            in = resource.getInputStream();
            Yaml props = new Yaml();
            Object obj = props.loadAs(in,Map.class);
            Map<Object,Object> param = (Map<Object, Object>) obj;

            for(Map.Entry<Object,Object> entry:param.entrySet()){
                Object key = entry.getKey();
                Object val = entry.getValue();
                if (keys.length != 0 && !keys[0].equals(String.valueOf(key))){
                    continue;
                }
                if(val != null){
                    if(val instanceof Map){
                        forEachYaml(key,(Map<Object, Object>) val, 1, keys);
                    }else{
                        result.put(String.valueOf(key), val.toString());
                    }
                }
            }
            return result;
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage(),e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(),e);
        } finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(),e);
                }
            }
        }
        return null;
    }

    /**
     * 根据key获取值
     * @param key
     * @return
     */
    public static String getValue(String key) throws FileNotFoundException {
        Map<String,String> map = getYmlByFileName(null);
        if(map==null) {
            return null;
        }
        return map.get(key);
    }


    /**
     * 遍历yml文件，获取map集合
     * @param key_str
     * @param obj
     * @param i
     * @param keys
     * @return
     */
    public static Map<String,String> forEachYaml(Object key_str,Map<Object, Object> obj, int i, String... keys){
        for(Map.Entry<Object,Object> entry:obj.entrySet()){
            Object key = entry.getKey();
            Object val = entry.getValue();
            if (keys.length > i && !keys[i].equals(String.valueOf(key))){
                continue;
            }
            String str_new = "";
            if(!StringUtil.isEmpty(String.valueOf(key_str))){
                str_new = key_str+ "."+key;
            }else{
                str_new = String.valueOf(key);
            }
            if(val != null){
                if(val instanceof Map){
                    forEachYaml(str_new,(Map<Object, Object>) val, ++i, keys);
                    i--;
                }else{

                    result.put(str_new,val.toString());
                }
            }
        }

        return result;
    }


    /**
     * 获取bootstrap.yml的name
     * @return
     */
    public static String getApplicationName() throws FileNotFoundException {
        return getYmlByFileName(bootstrap_file).get("server.port");
    }

    /**
     * 获取bootstrap.yml的name
     * @return
     */
    public static String getApplicationName1() throws FileNotFoundException {
        String name = getYmlByFileName(bootstrap_file).get("spring.application.name");
        return name + "center";
    }

    public static List<String> getFirstYmlByFileName(String  filePath){
        List<String> result = new ArrayList<>();
        if(filePath == null) {
            filePath = bootstrap_file;
        }
        InputStream in = null;
        try {
//            in = new BufferedInputStream(new FileInputStream(file));
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(filePath);
            Resource resource = resources[0];//获得文件流，因为在jar文件中，不能直接通过文件资源路径拿到文件，但是可以在jar包中拿到文件流
            in = resource.getInputStream();
            Yaml props = new Yaml();
            Object obj = props.loadAs(in,Map.class);
            Map<Object,Object> param = (Map<Object, Object>) obj;

            for(Map.Entry<Object,Object> entry:param.entrySet()){
                Object key = entry.getKey();
                if(key != null){
                    result.add(String.valueOf(key));
                }
            }
            return result;
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage(),e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(),e);
        } finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(),e);
                }
            }
        }
        return null;
    }


    public static void main(String[] args) throws FileNotFoundException, ScriptException {
//        String value = getValue("0f02d820.tableNumber");
//        String value1 = getValue("0f02d820.magnification");
//        System.out.println(value);
//        ScriptEngineManager manager = new ScriptEngineManager();
//        ScriptEngine engine = manager.getEngineByName("js");
//        Object result = engine.eval(value1);
//        System.out.println(result);
//
        Map<String, String> ymlByFileName = getYmlByFileName(null);
        System.out.println(ymlByFileName);

//        String key  = "45323788_e_peak";
//        int i = key.indexOf("_");
//        String substring = key.substring(i+1, key.length());
//        System.out.println(substring);
    }
}
